/*=============================================================================== 
 * SQLHelper.cs
 * author:csyingwu
 * 
 * 
 * 
 */
//============================================================================

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Collections;

namespace Kaidou.Util
{

    /// <summary>
    /// The SqlHelper class is intended to encapsulate high performance, 
    /// scalable best practices for common uses of SqlClient.
    /// </summary>
    public sealed class SqlDB
    {

        // Database connection 
        private SqlConnection _dbConn;
        private SqlTransaction _Transaction;
        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Default Constructor and open connect
        /// </summary>
        public SqlDB()
        {
            _Transaction = null;
            _dbConn = DBConnection.CreateInstance();
            try
            {
                _dbConn.Open();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB " + ex.Message);
                throw new Exception("SqlDB " + ex.Message);
            }
        }


        public void Close()
        {
            if (null != _dbConn)
            {
                if (_dbConn.State == ConnectionState.Open)
                    _dbConn.Close();
            }
        }

        public void TransBegin()
        {
            try
            {
                _Transaction = _dbConn.BeginTransaction();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB - TransBegin " + ex.Message);
                throw new Exception("SqlDB " + ex.Message);
            }
        }

        public void TransRollback()
        {
            try
            {
                _Transaction.Rollback();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB - TransRollback " + ex.Message);
                throw new Exception("SqlDB TransRollback " + ex.Message);
            }
        }

        public void TransCommit()
        {
            try
            {
                _Transaction.Commit();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB - TransCommit " + ex.Message);
                throw new Exception("SqlDB TransCommit " + ex.Message);
            }
        }


        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteCmd(string cmdText, SqlParameter[] SqlParams)
        /// </remarks>
        /// <param name="cmdText">the stored procedure name or T-SQL command</param>
        /// <param name="SqlParams">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public int ExecuteCmd(string cmdText, SqlParameter[] SqlParams)
        {
            int val = 0;

            SqlCommand cmd = new SqlCommand();

            try
            {
                PrepareCommand(cmd, _dbConn, _Transaction, CommandType.Text, cmdText, SqlParams);
                val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB - ExecuteCmd " + ex.Message + ex.StackTrace + ex.Source);
                throw new Exception("SqlDB - ExecuteCmd " + ex.Message + ex.StackTrace + ex.Source);
            }

            return val;
        }

        public int ExecuteProcedure(string cmdText, ref SqlParameter[] SqlParams)
        {
            int val = 0;

            SqlCommand cmd = new SqlCommand();

            try
            {
                PrepareCommand(cmd, _dbConn, _Transaction, CommandType.StoredProcedure, cmdText, SqlParams);
                val = cmd.ExecuteNonQuery();
                if (SqlParams != null)
                {
                    foreach (SqlParameter parm in SqlParams)
                    {
                        if (parm.Direction == ParameterDirection.Output || parm.Direction == ParameterDirection.InputOutput || parm.Direction == ParameterDirection.ReturnValue)
                            parm.Value = cmd.Parameters[parm.ParameterName].Value;
                    }
                }
                cmd.Parameters.Clear();
                cmd.Dispose();
            }
            catch (Exception ex)
            {
                //throw ex;
                LogManager.error("SqlDB - ExecuteProcedure " + ex.Message);
                throw new Exception("SqlDB - ExecuteProcedure " + ex.Message + ex.StackTrace + ex.Source);
            }

            return val;
        }
        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = GetDataCmd(string cmdText, params SqlParameter[] SqlParams)
        /// </remarks>        
        /// <param name="cmdText">the stored procedure name or T-SQL command</param>
        /// <param name="SqlParams">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public SqlDataReader GetDataCmd(string cmdText, params SqlParameter[] SqlParams)
        {

            SqlCommand cmd = new SqlCommand();

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the             
            try
            {
                PrepareCommand(cmd, _dbConn, _Transaction, CommandType.Text, cmdText, SqlParams);
                SqlDataReader rdr = cmd.ExecuteReader();

                cmd.Parameters.Clear();
                cmd.Dispose();
                return rdr;
            }
            catch (Exception ex)
            {
                _dbConn.Close();
                LogManager.error("SqlDB - GetDataCmd " + ex.Message);
                throw new Exception("SqlDB - GetDataCmd " + ex.Message + ex.StackTrace + ex.Source);

            }
            return null;
        }
        public SqlDataReader GetLargeDataCmd(string cmdText, int timeout, params SqlParameter[] SqlParams)
        {

            SqlCommand cmd = new SqlCommand();

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the             
            try
            {
                PrepareCommand(cmd, _dbConn, _Transaction, CommandType.Text, cmdText, SqlParams);
                SqlDataReader rdr = cmd.ExecuteReader();
                cmd.CommandTimeout = timeout;
                cmd.Parameters.Clear();
                cmd.Dispose();
                return rdr;
            }
            catch (Exception ex)
            {
                _dbConn.Close();
                LogManager.error("SqlDB - GetDataCmd " + ex.Message + " SQL:" + cmdText);
                throw ex;
            }
            return null;
        }
        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            cmd.CommandTimeout = 200;
            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }
    }
}